package design_pattern.ReadWriteLock;

/**
 * @Author: 蔡翔
 * @Date: 2019/11/4 9:17
 * @Version 1.0
 */
public class ShareDate {
    //这个共享数据 就定义成buffer 就好了。
    private final char[] buffer;
    private final ReadWriteLock lock = new ReadWriteLock();
    public ShareDate(int size){
        //之所以可以先赋值，再初始化就是因为，buffer是一个引用类型 buffer改变了，this.buffer也改变了。
        this.buffer = new char[size];
        //做初始化
        for(int i = 0;i<size;i++){
            this.buffer[i] = '*';
        }
    }

    public char[] read() throws InterruptedException {
        try {
            lock.readLock();
            return doRead();
        }finally {
            lock.readUnlock();
        }
    }

    public void write(char c){
        try {
            lock.writeLock();
            //doWrite
            this.doWrite(c);
        }catch (Exception e){

        }
        finally {
            lock.writeUnlock();

        }
    }

    private void doWrite(char c) {
        for(int i=0;i<buffer.length;i++){
            buffer[i] = c;
            slowly(10);
        }
    }

    private char[] doRead() {
        //执行一些doRead 的方法。
        char[] newBuf = new char[this.buffer.length];
        for(int i = 0;i<this.buffer.length;i++){
            newBuf[i] = this.buffer[i];
        }
        //短暂休眠一下
        slowly(50);
        return newBuf;
    }

    private void slowly(int ms) {
        try {
            Thread.sleep(ms);
        }catch (Exception e){

        }
    }
}
